package leetcode.code1032;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

public class StreamChecker {

	Node root;
	Queue<Node> queue;

	public StreamChecker(String[] words) {
		root = new Node();
		for (String str : words) {
			Node node = root;
			for (char c : str.toCharArray()) {
				node = node.computeIfAbsent(c, key -> new Node());
			}
			node.end = true;
		}
		queue = new LinkedList<>();
	}

	public boolean query(char letter) {
		int size = queue.size();
		boolean ans = false;
		while (size > 0) {
			Node cur = queue.poll();
			if (cur.containsKey(letter)) {
				Node next = cur.get(letter);
				if (next.end)
					ans = true;
				queue.add(next);
			}
			size--;
		}
		if (root.containsKey(letter)) {
			Node cur = root.get(letter);
			queue.add(cur);
			if (cur.end)
				ans = true;
		}
		return ans;
	}

	class Node extends HashMap<Character, Node> {
		boolean end;
	}
}
